import axios from 'axios'
import React, { useRef } from 'react'

interface PropsType {
  onChange?: (params: { type: string, url: string }[]) => void
}

export const Upload: React.FC<PropsType> = ({ onChange }) => {
  const input = useRef<null | HTMLInputElement>(null)
  const handleChange = async () => {
    const files = input.current?.files
    if (files) {
      const requests = Array.from(files).map(file => {
        const formData = new FormData();
        formData.append('file', file, file.name)
        return axios.post('/xxx/upload', formData)
      });
      const result = await Promise.all(requests)
      const s =  result.map(v => {
        return {
          url:  v.data.data.url,
          type: v.data.type
        }
      })
      onChange && onChange(s)
    }
  }

  return <div style={{ height: '100%', width: 30, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
    <input type="file" style={{ display: 'none' }} ref={input} onChange={() => handleChange()} multiple/>
    <span onClick={() => input.current?.click()} style={{ fontSize: 30 }}>+</span>
  </div>
}